package top.wuyang.study.javawebjdbc.workcp;

import top.wuyang.study.javawebjdbc.dao.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class TbCpDAO {

    public static int insert(TbCp tbCp) throws Exception{
        Connection conn = DBHelper.getConnection();
        String sql = "insert into tb_computer (changshang, dnjj, price) values (?, ?, ?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,tbCp.getChangshang());
        ps.setString(2,tbCp.getDnjj());
        ps.setInt(3,tbCp.getPrice());
        int i = ps.executeUpdate();
        conn.close();
        return i;
    }

    public static List<TbCp> query() throws Exception{
        List<TbCp> list = new ArrayList<>();
        Connection conn = DBHelper.getConnection();
        String sql = "select * from tb_computer";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            TbCp tbCp = new TbCp();
            tbCp.setId(rs.getInt("id"));
            tbCp.setChangshang(rs.getString("changshang"));
            tbCp.setDnjj(rs.getString("dnjj"));
            tbCp.setPrice(rs.getInt("price"));
            list.add(tbCp);
        }
        conn.close();
        return list;
    }

    public static int delete(Integer id) throws Exception{
        Connection conn = DBHelper.getConnection();
        String sql = "delete from tb_computer where id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,id);
        int i = ps.executeUpdate();
        conn.close();
        return i;
    }

}
